class MyBlockingQueue{
    private String[] elems = null;
    private int head = 0;
    private int tail = 0;
    private int size = 0;
    private Object locker = new Object();
    //构造方法——初始化数组大小
    public MyBlockingQueue(int capacity){
        elems = new String[capacity];
    }

    //put方法——队列满时需要阻塞
    public void put(String elem) throws InterruptedException {
        synchronized (locker) {
            while(size >= elems.length) {
                //这里后续需要写代码让它阻塞
                    locker.wait();
            }
            //放入元素
            elems[tail] = elem;
            tail++;
            if (tail >= elems.length) {
                tail = 0;
            }
            size++;
            locker.notify();
        }
    }
    //take方法——队列为空时需要阻塞
    public String take() throws InterruptedException {
        String ret = null;
        synchronized (locker){
        while (size == 0){
            //这里后续需要阻塞
            locker.wait();
        }
        ret = elems[head];
        head++;
        if(head >= elems.length){
            head = 0;
        }
        size--;
        locker.notify();
        }
        return ret;
    }
}

public class ThreadDemo2 {
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue(1024);
        Thread t1 = new Thread(()->{
            int count = 0;
            while (true) {
                try {
                    queue.put(String.valueOf(count));
                    System.out.println("生产元素"+count);
                    count++;

                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        Thread t2 = new Thread(()->{
            while(true){
                try {
                    String s = queue.take();
                    System.out.println("消费元素"+s);
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t1.start();
        t2.start();
    }
}
